const { body } = require('express-validator');
const { User } = require('../../models');
const bcrypt = require('bcryptjs');

// 修改密码验证
exports.changePassword = [
    body('oldPassword')
        .notEmpty().withMessage('原密码不能为空').bail(),
    
    body('newPassword')
        .notEmpty().withMessage('新密码不能为空').bail()
        .isLength({ min: 6 }).withMessage('新密码至少6个字符').bail()
        .custom((value, { req }) => {
            if (value === req.body.oldPassword) {
                throw new Error('新密码不能与原密码相同');
            }
            return true;
        })
];

// 修改用户信息验证
exports.updateUserInfo = [
    body('email')
        .optional()
        .isEmail().withMessage('邮箱格式不正确').bail()
        .custom(async (email, { req }) => {
            const existingUser = await User.findOne({ 
                email, 
                _id: { $ne: req.user.userinfo.id } 
            });
            if (existingUser) {
                throw new Error('该邮箱已被使用');
            }
            return true;
        }),

    body('phone')
        .optional()
        .matches(/^1[3-9]\d{9}$/).withMessage('请输入有效的手机号').bail()
        .custom(async (phone, { req }) => {
            const existingUser = await User.findOne({ 
                phone, 
                _id: { $ne: req.user.userinfo.id } 
            });
            if (existingUser) {
                throw new Error('该手机号已被使用');
            }
            return true;
        })
]; 